﻿using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Framework.Net.Xmpp.InstantMessaging;
using Microsoft.Practices.Unity;
using XClient.Views;

namespace XClient
{
    /// <summary>
    /// Interaction logic for MainView.xaml
    /// </summary>
    public partial class MainView : UserControl
    {
        #region · Fields ·

        private IUnityContainer container;
        
        #endregion

        #region · Constructors ·

        public MainView(IUnityContainer container)
        {
            InitializeComponent();
            this.container = container;

            this.LoginScreen.Content = this.container.Resolve<LoginView>();
            this.SessionView.Content = this.container.Resolve<SessionView>();            

            this.WireEvents();
        }

        #endregion

        #region · Private Methods ·

        private void WireEvents()
        {
            this.container.Resolve<XmppSession>().StateChanged += new System.EventHandler<XmppSessionStateChangedEventArgs>(OnSessionStateChanged);
        }

        #endregion

        #region · Event Handlers ·

        private void OnShowLogin(object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, "ShowLogin", true);
        }

        private void OnSessionStateChanged(object sender, XmppSessionStateChangedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(
                DispatcherPriority.ApplicationIdle,
                new ThreadStart(delegate
                {
                    switch (e.NewState)
                    {
                        case XmppSessionState.LoggedIn:
                            VisualStateManager.GoToState(this, "LoggedIn", true);
                            break;

                        case XmppSessionState.LoggingIn:
                            VisualStateManager.GoToState(this, "LoggingIn", false);
                            break;

                        case XmppSessionState.LoggingOut:
                            VisualStateManager.GoToState(this, "LoggingOut", true);
                            break;

                        case XmppSessionState.Error:
                            VisualStateManager.GoToState(this, "Error", true);
                            break;
                    }
                }));
        }

        #endregion
    }
}
